package com.group56.model.dao.Impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.group56.model.dao.OrderDAO;
import com.group56.model.entity.Order;
import com.group56.model.tools.jsonFileProcessor;
import com.group56.utils.DBSrcMenu;

import java.util.ArrayList;

public class OrderDAOImpl implements OrderDAO {

    public static void main(String[] args) {
        Order order1 = new Order("","1","1");
        Order order2 = new Order("","1","2");
        Order order3 = new Order("","1","3");
        OrderDAOImpl test = new OrderDAOImpl();
        test.insert(order1);
        test.insert(order2);
        test.insert(order3);
        System.out.println(test.selectByCustomer("1"));
    }

    public boolean insert(Order order){
        jsonFileProcessor file = new jsonFileProcessor(DBSrcMenu.ORDER_JSON.getSrc());
        StringBuffer buffer = file.read();
        ArrayList<Order> records = new ArrayList<>();
        if (!buffer.toString().equals("")) {
            records = new Gson().fromJson(buffer.toString(), new TypeToken<ArrayList<Order>>() {}.getType());
            if (records.size()!=0)
                order.setOrderID(String.valueOf(Integer.parseInt(records.get(records.size() - 1).getOrderID())+1));
            else
                order.setOrderID("1");
        }
        else
            order.setOrderID("1");
        records.add(order);
        return file.rewrite(records);
    }

    public ArrayList<Order> selectByCustomer(String customerID){
        StringBuffer buffer = new jsonFileProcessor(DBSrcMenu.ORDER_JSON.getSrc()).read();
        if (!buffer.toString().equals("")) {
            ArrayList<Order> records = new Gson().fromJson(buffer.toString(), new TypeToken<ArrayList<Order>>(){}.getType());
            ArrayList<Order> res = new ArrayList<>();
            for (Order s : records)
                if (s.getCustomerID().equals(customerID))
                    res.add(s);
            return res;
        }
        return null;
    }

    public boolean delete(String orderID){
        jsonFileProcessor file = new jsonFileProcessor(DBSrcMenu.ORDER_JSON.getSrc());
        StringBuffer buffer = file.read();
        if (!buffer.toString().equals("")) {
            ArrayList<Order> records = new Gson().fromJson(buffer.toString(), new TypeToken<ArrayList<Order>>(){}.getType());
            for (Order s : records)
                if (s.getOrderID().equals(orderID)){
                    records.remove(s);
                    return file.rewrite(records);
                }
        }
        return false;
    }

    public boolean update(Order order, String orderID){
        if (delete(orderID))
            return insert(order);
        return false;
    }

}
